package com.sunday.common.mongo.study.aggregate.tools;

import org.bson.Document;
import org.bson.types.Decimal128;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;

import java.util.Arrays;
import java.util.stream.Collectors;

public class MongoDBCompassGenerateTools {

    public static Aggregation generate() {
        return Aggregation.newAggregation(Arrays.asList(new Document("$match",
                                new Document("user_id", Decimal128.parse("1646819445571584043"))),
                        new Document("$group",
                                new Document("_id", "$user_id")
                                        .append("role_ids",
                                                new Document("$addToSet", "$role_id"))),
                        new Document("$lookup",
                                new Document("from", "sunday_role_permissions")
                                        .append("let",
                                                new Document("role_ids", "$role_ids"))
                                        .append("pipeline", Arrays.asList(new Document("$match",
                                                        new Document("$expr",
                                                                new Document("$and", Arrays.asList(new Document("$in", Arrays.asList("$role_id", "$$role_ids")))))),
                                                new Document("$group",
                                                        new Document("_id", "$permissions_id"))))
                                        .append("as", "permission_ids")),
                        new Document("$lookup",
                                new Document("from", "sunday_permissions")
                                        .append("let",
                                                new Document("permission_id", "$permission_ids._id"))
                                        .append("pipeline", Arrays.asList(new Document("$match",
                                                        new Document("$expr",
                                                                new Document("$and", Arrays.asList(new Document("$in", Arrays.asList("$_id", "$$permission_id")))))),
                                                new Document("$project",
                                                        new Document("category", 1L)
                                                                .append("url", 1L)
                                                                .append("position", 1L)
                                                                .append("code", 1L))))
                                        .append("as", "permissions")),
                        new Document("$unset", Arrays.asList("role_ids", "permission_ids")))
                .stream().map(d -> (AggregationOperation) context -> d).toList());
    }

}
